package com.beta.admin.controller;

import com.beta.admin.request.auth.AuthRequest;
import com.beta.admin.support.web.BaseController;
import com.beta.common.exception.ControllerException;
import com.beta.common.web.ContentType;
import com.beta.entity.Admins;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

/**
 * Created by vector on 2017/1/1.
 */
@RestController
@RequestMapping(value = RequestMappingConstants.MAPPING_PREFIX)
public class LoginController extends BaseController {

    @PostMapping(value = "/login", produces = ContentType.JSON, consumes = ContentType.JSON)
    public Object login(@Valid @RequestBody AuthRequest authRequest) {
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(new UsernamePasswordToken(authRequest.getUsername(), authRequest.getPassword()));
            Admins currentAdmin = (Admins) subject.getPrincipal();
            return ok(HttpServletResponse.SC_CREATED, currentAdmin);
        } catch (UnknownAccountException exception) {
            throw new ControllerException("E00106");
        } catch (IncorrectCredentialsException exception) {
            throw new ControllerException("E00105");
        } catch (Exception exception) {
            throw new ControllerException(exception);
        }
    }

    @GetMapping(value = "/logout", produces = ContentType.JSON)
    public Object logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return ok();
    }

}
